<template>
  <div class="borrow-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">我的借阅</h1>
      <p class="page-subtitle">查看您的借阅记录</p>
    </div>

    <!-- 统计信息 -->
    <div class="stats-grid">
      <el-card class="stat-card" shadow="never">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-number">{{ stats.borrowing }}</div>
            <div class="stat-label">借阅中</div>
          </div>
          <div class="stat-icon borrowing">
            <el-icon><Files /></el-icon>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="never">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-number">{{ stats.returned }}</div>
            <div class="stat-label">已归还</div>
          </div>
          <div class="stat-icon returned">
            <el-icon><Check /></el-icon>
          </div>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="never">
        <div class="stat-content">
          <div class="stat-info">
            <div class="stat-number">{{ stats.overdue }}</div>
            <div class="stat-label">已逾期</div>
          </div>
          <div class="stat-icon overdue">
            <el-icon><Warning /></el-icon>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="借阅中" :value="0" />
            <el-option label="已归还" :value="1" />
            <el-option label="已逾期" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchBorrows">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 借阅记录列表 -->
    <el-card class="list-card" shadow="never">
      <template #header>
        <div class="card-header">
          <h3>借阅记录</h3>
          <el-button type="primary" @click="refreshBorrows">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <div v-if="borrows.length === 0 && !loading" class="empty-state">
        <el-icon><Reading /></el-icon>
        <p>暂无借阅记录</p>
        <el-button type="primary" @click="$router.push('/books')">开始借阅</el-button>
      </div>

      <div v-else class="borrow-records">
        <div 
          v-for="borrow in borrows" 
          :key="borrow.id"
          class="borrow-record-item"
        >
          <div class="book-cover">
            <el-icon><Reading /></el-icon>
          </div>
          
          <div class="book-info">
            <div class="book-title">{{ borrow.bookName || '未知图书' }}</div>
            <div class="book-meta">
              <span class="meta-item">
                <span class="meta-label">图书ID：</span>
                <span class="meta-value">{{ borrow.bookId || '无' }}</span>
              </span>
            </div>
          </div>

          <div class="borrow-dates">
            <div class="date-item">
              <span class="date-label">借阅日期</span>
              <span class="date-value">{{ formatDate(borrow.borrowDate) }}</span>
            </div>
            <div class="date-item">
              <span class="date-label">应还日期</span>
              <span class="date-value">{{ formatDate(borrow.dueDate) }}</span>
            </div>
            <div v-if="borrow.returnDate" class="date-item">
              <span class="date-label">实际还书</span>
              <span class="date-value">{{ formatDate(borrow.returnDate) }}</span>
            </div>
          </div>

          <div class="borrow-status">
            <el-tag 
              :type="getBorrowStatusType(borrow.status)" 
              :class="getBorrowStatusClass(borrow.status)"
              size="large"
            >
              {{ getBorrowStatusText(borrow.status) }}
            </el-tag>

          </div>

          <div class="borrow-actions">
            <el-button
              v-if="canReturn(borrow)"
              type="success"
              size="small"
              @click="returnBook(borrow)"
            >
              归还
            </el-button>
            <el-button
              v-if="canRenew(borrow)"
              type="primary"
              size="small"
              @click="renewBook(borrow)"
            >
              续借
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="viewDetails(borrow)"
            >
              详情
            </el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="borrows.length > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()
const loading = ref(false)
const borrows = ref([])

const searchForm = ref({
  status: null
})

const pagination = ref({
  current: 1,
  size: 10,
  total: 0
})

// 统计信息
const stats = computed(() => {
  const borrowing = borrows.value.filter(b => b.status === 'BORROWED' || b.status === '0').length
  const returned = borrows.value.filter(b => b.status === 'RETURNED' || b.status === '1').length
  const overdue = borrows.value.filter(b => b.status === 'OVERDUE' || b.status === '2').length
  
  return { borrowing, returned, overdue }
})

// 获取借阅记录
const fetchBorrows = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.value.current,
      size: pagination.value.size,
      userId: authStore.user && authStore.user.id,
      status: searchForm.value.status
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await request.get('/borrows/page', { params })
    if (response.code === 200) {
      const data = response.data
      borrows.value = data.records || []
      pagination.value.total = data.total || 0
    }
  } catch (error) {
    console.error('获取借阅记录失败:', error)
    ElMessage.error('获取借阅记录失败')
  }
  loading.value = false
}

// 搜索借阅记录
const searchBorrows = () => {
  pagination.value.current = 1
  fetchBorrows()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = { status: null }
  pagination.value.current = 1
  fetchBorrows()
}

// 刷新借阅记录
const refreshBorrows = () => {
  fetchBorrows()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.value.size = val
  pagination.value.current = 1
  fetchBorrows()
}

const handleCurrentChange = (val) => {
  pagination.value.current = val
  fetchBorrows()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 状态相关方法
const getBorrowStatusType = (status) => {
  switch (status) {
    case 'BORROWED':
    case '0': return 'warning'  // 借阅中
    case 'RETURNED':
    case '1': return 'success'  // 已归还
    case 'OVERDUE':
    case '2': return 'danger'   // 已逾期
    default: return 'info'
  }
}

const getBorrowStatusClass = (status) => {
  switch (status) {
    case 'BORROWED':
    case '0': return 'status-borrowing'
    case 'RETURNED':
    case '1': return 'status-returned'
    case 'OVERDUE':
    case '2': return 'status-overdue'
    default: return ''
  }
}

const getBorrowStatusText = (status) => {
  switch (status) {
    case 'BORROWED':
    case '0': return '借阅中'
    case 'RETURNED':
    case '1': return '已归还'
    case 'OVERDUE':
    case '2': return '已逾期'
    default: return '未知'
  }
}

// 检查是否可以还书（兼容不同状态格式）
const canReturn = (borrow) => {
  const status = borrow.status
  // 兼容字符串格式和数字格式
  return status === 'BORROWED' || status === 'OVERDUE' || status === '0' || status === '2'
}

// 是否可以续借
const canRenew = (borrow) => {
  const status = borrow.status
  // 只有借阅中状态且未逾期可以续借
  const isBorrowed = status === 'BORROWED' || status === '0'
  const notOverdue = new Date(borrow.dueDate) > new Date()
  return isBorrowed && notOverdue
}

// 归还图书
const returnBook = async (borrow) => {
  try {
    await ElMessageBox.confirm(
      `确定要归还《${borrow.bookName}》吗？`,
      '确认归还',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await request.post(`/borrows/return/${borrow.id}`)
    if (response.code === 200) {
      ElMessage.success('归还成功')
      fetchBorrows()
    } else {
      ElMessage.error(response.message || '归还失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      // 检查是否是"图书已归还"的情况
      if (error.message && error.message.includes('图书已归还')) {
        ElMessage.success('图书已经归还了')
        fetchBorrows() // 刷新列表
      } else {
        console.error('归还图书失败:', error)
        ElMessage.error(error.message || '归还失败')
      }
    }
  }
}

// 续借图书
const renewBook = async (borrow) => {
  try {
    await ElMessageBox.confirm(
      `确定要续借《${borrow.bookName}》吗？续借后借阅期限将延长30天。`,
      '确认续借',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    const response = await request.post(`/borrows/renew/${borrow.id}`, null, {
      params: { days: 30 }
    })
    if (response.code === 200) {
      ElMessage.success('续借成功')
      fetchBorrows()
    } else {
      ElMessage.error(response.message || '续借失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('续借图书失败:', error)
      ElMessage.error(error.message || '续借失败')
    }
  }
}

// 查看详情
const viewDetails = (borrow) => {
  ElMessageBox.alert(
    `
    <div style="text-align: left;">
      <p><strong>图书信息：</strong></p>
      <p>书名：${borrow.book?.name || '未知'}</p>
      <p>作者：${borrow.book?.author || '未知'}</p>
      <p>ISBN：${borrow.book?.isbn || '无'}</p>
      <br>
      <p><strong>借阅信息：</strong></p>
      <p>借阅日期：${formatDate(borrow.borrowDate)}</p>
      <p>应还日期：${formatDate(borrow.dueDate)}</p>
      ${borrow.returnDate ? `<p>归还日期：${formatDate(borrow.returnDate)}</p>` : ''}
      <p>状态：${getBorrowStatusText(borrow.status)}</p>
    </div>
    `,
    '借阅详情',
    {
      confirmButtonText: '确定',
      dangerouslyUseHTMLString: true
    }
  )
}

onMounted(() => {
  fetchBorrows()
})
</script>

<style scoped>
.borrow-list {
  max-width: 1200px;
  margin: 0 auto;
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  color: #262626;
  margin-bottom: 8px;
  font-weight: 600;
}

.page-subtitle {
  font-size: 16px;
  color: #595959;
  margin: 0;
}

/* 统计卡片 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.stat-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  transition: box-shadow 0.2s;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.stat-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #262626;
  line-height: 1.2;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 16px;
  color: #595959;
  font-weight: 500;
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #ffffff;
}

.stat-icon.borrowing {
  background-color: #faad14;
}

.stat-icon.returned {
  background-color: #52c41a;
}

.stat-icon.overdue {
  background-color: #ff4d4f;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 24px;
  border: 1px solid #e8e8e8;
}

.search-form {
  margin: 0;
}

/* 列表卡片 */
.list-card {
  border: 1px solid #e8e8e8;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: #262626;
  font-weight: 600;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #8c8c8c;
}

.empty-state .el-icon {
  font-size: 64px;
  margin-bottom: 16px;
  color: #d9d9d9;
}

.empty-state p {
  margin: 0 0 24px 0;
  font-size: 18px;
}

/* 借阅记录 */
.borrow-records {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.borrow-record-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.2s;
}

.borrow-record-item:hover {
  border-color: #d9d9d9;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.book-cover {
  width: 60px;
  height: 80px;
  background-color: #f0f8ff;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: #1890ff;
  flex-shrink: 0;
}

.book-info {
  flex: 2;
  min-width: 0;
}

.book-title {
  font-size: 18px;
  color: #262626;
  font-weight: 600;
  margin-bottom: 8px;
  line-height: 1.4;
}

.book-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.meta-item {
  font-size: 14px;
  color: #8c8c8c;
}

.meta-label {
  font-weight: 500;
}

.meta-value {
  color: #595959;
}

.borrow-dates {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin: 0 20px;
}

.date-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.date-label {
  font-size: 12px;
  color: #8c8c8c;
  margin-bottom: 2px;
}

.date-value {
  font-size: 14px;
  color: #262626;
  font-weight: 500;
}

.borrow-status {
  margin: 0 20px;
}

.borrow-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex-shrink: 0;
}

/* 状态标签 */
.status-borrowing {
  background-color: #fff2e8 !important;
  color: #faad14 !important;
  border-color: #ffd591 !important;
}

.status-returned {
  background-color: #f6ffed !important;
  color: #52c41a !important;
  border-color: #b7eb8f !important;
}

.status-overdue {
  background-color: #fff2f0 !important;
  color: #ff4d4f !important;
  border-color: #ffadd2 !important;
}

/* 分页 */
.pagination-container {
  margin-top: 24px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .borrow-record-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .book-cover {
    align-self: center;
    margin-right: 0;
  }
  
  .book-info,
  .borrow-dates {
    margin: 0;
    width: 100%;
  }
  
  .borrow-dates {
    flex-direction: row;
    justify-content: space-around;
  }
  
  .borrow-actions {
    flex-direction: row;
    justify-content: center;
    width: 100%;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .stat-number {
    font-size: 28px;
  }
}
</style> 